package main

import (
	"fmt"
	"sync"
	"unsafe"
)

type Singleton struct {
	data string
}

var singleInstance *Singleton
var once sync.Once

func GetSingletonInstance() *Singleton {
	once.Do(func() {
		fmt.Println("创建实例")
		singleInstance = new(Singleton)
	})
	return singleInstance
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 5; i++ {
		wg.Add(1)
		go func() {
			obj := GetSingletonInstance()

			//循环中每次输出的实例的地址都是相同的,而且上面的"创建实例"只会输出一次
			fmt.Println(unsafe.Pointer(obj))
			wg.Done()
		}()
	}
	wg.Wait()
}
